import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authAPI, roleAPI } from '@/utils/api'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref('')
  const userInfo = ref({})
  const permissions = ref([])
  const menuRoutes = ref([])
  const userRoles = ref([]) // 存储用户角色列表
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userRole = computed(() => userInfo.value?.role || '')
  const username = computed(() => userInfo.value?.username || '')
  const name = computed(() => userInfo.value?.name || '')
  const avatar = computed(() => userInfo.value?.avatar || '')
  
  // 判断是否有权限
  const hasPermission = (permission) => {
    // 管理员拥有所有权限
    if (userRole.value === 'admin') {
      return true
    }
    
    if (!permissions.value || permissions.value.length === 0) {
      return false
    }
    
    // 如果是数组，检查是否有任一权限
    if (Array.isArray(permission)) {
      return permission.some(p => permissions.value.includes(p))
    }
    
    // 单个权限检查
    return permissions.value.includes(permission)
  }
  
  // 判断是否有角色
  const hasRole = (role) => {
    if (!userRole.value) return false
    
    // 多角色检查
    if (Array.isArray(role)) {
      return role.includes(userRole.value)
    }
    
    // 单角色检查
    return userRole.value === role
  }

  // 设置用户token
  function setToken(newToken, showLogs = true) {
    // 更新store中的token
    token.value = newToken
    
    // 同时更新localStorage中的token
    if (newToken) {
      localStorage.setItem('token', newToken)
    } else {
      localStorage.removeItem('token')
    }
  }

  // 设置用户信息
  function setUserInfo(info) {
    userInfo.value = info
    if (info?.roleInfo?.permissions) {
      permissions.value = info.roleInfo.permissions
    } else if (info?.permissions) {
      permissions.value = info.permissions
    } else {
      // 如果没有权限信息，给予基本权限，确保用户至少能看到Dashboard
      permissions.value = ['dashboard:read']
    }
  }
  
  // 设置菜单路由
  function setMenuRoutes(routes) {
    menuRoutes.value = routes
  }
  
  // 获取用户信息
  async function fetchUserInfo() {
    try {
      const res = await authAPI.getUserInfo()
      setUserInfo(res.data.user)
      // 获取用户角色信息
      await fetchUserRoles()
      return res.data
    } catch (error) {
      throw error
    }
  }
  
  // 获取用户角色信息
  async function fetchUserRoles() {
    try {
      const res = await roleAPI.getRoles()
      if (res.data && res.data.success) {
        userRoles.value = res.data.data.roles || []
      }
    } catch (error) {
      throw error
    }
  }
  
  // 登录
  async function login(loginData) {
    try {
      const res = await authAPI.login(loginData)
      setToken(res.data.accessToken)
      setUserInfo(res.data.user)
      return res
    } catch (error) {
      throw error
    }
  }
  
  // 注册
  async function register(registerData) {
    try {
      return await authAPI.register(registerData)
    } catch (error) {
      throw error
    }
  }
  
  // 修改密码
  async function changePassword(passwordData) {
    try {
      return await authAPI.changePassword(passwordData)
    } catch (error) {
      throw error
    }
  }

  // 退出登录
  function logout() {
    setToken('') // 使用setToken而不是直接设置，确保localStorage也被清除
    userInfo.value = {}
    permissions.value = []
    menuRoutes.value = []
    userRoles.value = []
  }

  return { 
    // 状态
    token, 
    userInfo, 
    permissions,
    menuRoutes,
    userRoles,
    
    // 计算属性
    isLoggedIn,
    userRole,
    username,
    name,
    avatar,
    
    // 方法
    hasPermission,
    hasRole,
    setToken,
    setUserInfo,
    setMenuRoutes,
    fetchUserInfo,
    fetchUserRoles,
    login,
    register,
    changePassword,
    logout
  }
}, {
  persist: {
    key: 'medical-user',
    storage: sessionStorage,
    paths: ['token', 'userInfo', 'permissions', 'menuRoutes', 'userRoles']
  }
}) 